//
//  SceneEditViewController.m
//  wAudioShare
//
//  Created by Anson on 14-11-6.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "SceneEditViewController.h"

#import "Utitlity.h"
#import "ActionPicker.h"
#import "SceneDeviceModel.h"
#import "SceneDeviceCell.h"

typedef NS_ENUM(NSInteger, SceneReqActionType) {
  
    SceneReqActionTypeAddNew,
    SceneReqActionTypeEdit,
    SceneReqActionTypeDelete
    
};

@interface SceneEditViewController ()
{
    
}



@property (copy) NSString *currenSceneId;

@end

@implementation SceneEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title =@"Scene";
    
    self.labelTitle.text = [self.sceneData objectForKey:@"label"];
    
    self.currenSceneId = [[self.sceneData objectForKey:@"scene"] stringValue];
    
//    NSMutableArray *dropDownItemList = [NSMutableArray arrayWithCapacity:self.deviceList.count];
//    for (NSDictionary *dict in self.deviceList) {
//        DropDownListItem *item = [[DropDownListItem alloc] init];
//        item.title = [dict objectForKey:@"Alias"];
//        item.userInfo = dict;
//        [dropDownItemList addObject:item];
//    }
//    [self.deviceDropDownListView setDataSource:dropDownItemList];
//    self.deviceDropDownListView.mSuperView = self.view;
    
    [self loadDeviceData];
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -


- (void)setArmConditionList:(NSArray *)list {
    
    _armConditionList = list;
    
}

#pragma mark - Http Request
-(void)loadDeviceData
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_listvalue&scene=%@", ipUrl, self.currenSceneId];
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        NSLog(@"%@", retJsonData);
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            //!由于空调返回的数据项有2个(因为有温度另外一个，需要使用该变量临时存储方便搜索
            NSMutableDictionary *thermostatDevList = [NSMutableDictionary dictionaryWithCapacity:10];
            
            NSArray *devList = [retJsonData objectForKey:@"data"];
            for (NSDictionary *dict in devList)
            {
                for (NSInteger i=0; i<self.canSelectDeviceList.count; i++) {
                    
                    NSDictionary *item = [self.canSelectDeviceList objectAtIndex:i];
                    NSString *deviceId = item[@"ZID"];
                    if ([deviceId isEqualToString:dict[@"did"]]) {
                        
                        SceneDeviceModel *data = [[SceneDeviceModel alloc] init];
                        data.deviceId = deviceId;
                        data.deviceType = [item[@"DeviceType"] integerValue];
                        data.title = item[@"Alias"];
                        switch (data.deviceType) {
                            case SceneDeviceTypeSwitch:
                            case SceneDeviceTypeMotor:
                            case SceneDeviceTypePowerMeter:
                            case SceneDeviceTypeDoorLock:
                            {
                                data.isOn = [dict[@"value"] boolValue];
                                break;
                            }
                            
                            case SceneDeviceTypeDimmer:
                            {
                                data.isOn = YES;
                                data.percent = [dict[@"value"] integerValue];
                                break;
                            }
                            case SceneDeviceTypeThermostat:{
                                
                                SceneDeviceModel *thermostatDev = thermostatDevList[deviceId];
                                if (thermostatDev) {
                                    
                                    thermostatDev.thermostatTemperature = [dict[@"value"] integerValue];
                                    data = thermostatDev;
                                    
                                }else {
                                
                                    data.mode = dict[@"value"];
                                    if (![data.mode.lowercaseString isEqualToString:@"off"]) {
                                        data.isOn = YES;
                                    }else
                                        break;
                                    
                                    if ([data.mode.lowercaseString isEqualToString:@"heat"] || [data.mode.lowercaseString isEqualToString:@"cool"]) {
                                        thermostatDevList[deviceId] = data;
                                        goto forbreak;
                                    }
                                }
                                
                                break;
                            }
                            default:
                                break;
                        }
                        [self.attachDeviceModelList addObject:data];
                        [self.canSelectDeviceList removeObjectAtIndex:i--];
                        break;
                        
                        forbreak: break;
                    }
                }

            }
            
            NSArray *armConditionList = [retJsonData objectForKey:@"conds"];
            for (NSDictionary *dict in armConditionList)
            {
                ArmModel *armModel = [[ArmModel alloc] initWithJSON:dict];
                for (ArmModel *item in _armConditionList) {
                    if (item.armId == armModel.armId) {
                        armModel.label = item.label;
                        break;
                    }
                }
                [self.attachDeviceModelList addObject:armModel];
            }
            
            [self.attachDeviceListView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
    }];
    }
}

- (void)loadArmListData {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {
        
        [activity startAnimating];
        
        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_listvalue&scene=%@", ipUrl, self.currenSceneId];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [activity stopAnimating];
            NSLog(@"error:%@",error);
        }];
    }
    
    
}

- (void)deleteAttachDevice:(id)modelData {
    
    if ([modelData isMemberOfClass:SceneDeviceModel.class]) {
        [self doDeleteAttachDevice:modelData];
    }else if ([modelData isMemberOfClass:ArmModel.class]) {
        [self reqSceneArmConditionActionType:SceneReqActionTypeDelete withArmModel:modelData];
    }
}

//!删除情景已添加的某个设备
- (void)doDeleteAttachDevice:(SceneDeviceModel *)modelData{
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];
    
     NSString *urlBase = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_del&scene=%@&did=%@", ipUrl, self.currenSceneId, modelData.deviceId ];
    NSString *urlStr = nil;
    switch (modelData.deviceType) {
        case SceneDeviceTypeMotor:
        case SceneDeviceTypePowerMeter:
        case SceneDeviceTypeSwitch:
        case SceneDeviceTypeDoorLock:
        {
            urlStr = [urlBase stringByAppendingString:@"&cmd=0x25&index=0"];
            break;
        }
        
        case SceneDeviceTypeDimmer:
        {
            urlStr = [urlBase stringByAppendingString:@"&cmd=0x26&index=0"];
            break;
        }
            
        case SceneDeviceTypeThermostat:
        {
            urlStr = [urlBase stringByAppendingString:@"&cmd=0x40&index=0"];
            break;
        }
        default:
            break;
    }
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType
                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                           [activity stopAnimating];
        
                           if (!responseObject) return;
                           NSDictionary *retJsonData = responseObject;
                           if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
                               [self.attachDeviceModelList removeObject:modelData];
                               [self.attachDeviceListView reloadData];
                           }
        
                        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                            [activity stopAnimating];
                            NSLog(@"error:%@",error);
                        }
    ];

    }
    
    [self.attachDeviceListView setEditing:!self.attachDeviceListView.editing animated:YES];
}

#pragma mark - UIButton
- (IBAction)deviceListSelectBtnClicked:(id)sender {
    [self doChoose:PICKER_VIEW_DEVICE_LIST_TAG];
}

- (IBAction)functionSelectedBtnClicked:(id)sender {
    [self doChoose:PICKER_VIEW_FUNCTION_LIST_TAG];
}

- (IBAction)addNewDeviceToScene:(id)sender {
    
    if (self.sceneAddArmConditionModel) {
        
        if (_currentEditAttachedDevice) {
            [self reqSceneArmConditionActionType:SceneReqActionTypeEdit withArmModel:self.sceneAddArmConditionModel];
        }else
            [self reqSceneArmConditionActionType:SceneReqActionTypeAddNew withArmModel:self.sceneAddArmConditionModel];
    
    }else {
    
        [self reqConfigSceneDevice:[self.selectedDeviceItemData objectForKey:@"ZID"]];
    }
}

- (void)reqConfigSceneDevice:(NSString *)deviceZID {

    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {
    
    [activity startAnimating];
    
    NSString *urlBase = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_add&scene=%@&did=%@", ipUrl, self.currenSceneId, deviceZID ];
    NSString *urlStr = nil;
    switch (_currentSelectDeviceType) {
        case SceneDeviceTypePowerMeter:
        case SceneDeviceTypeSwitch:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x25&index=0&value=%d", (self.addDeviceFunctionModel.isOn == YES ? 255 : 0)];
            break;
        }
    
        case SceneDeviceTypeMotor:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=38&index=0&value=%d", (self.addDeviceFunctionModel.isOn == YES ? 255 : 0)];
            break;
        }

        case SceneDeviceTypeThermostat:
        {
            if (self.addDeviceFunctionModel.isOn) {
                urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x40&index=0&value=%@", self.addDeviceFunctionModel.mode];
            }else
                urlStr = [urlBase stringByAppendingString:@"&cmd=0x40&index=0&value=Off"];
            break;
        }
            
        case SceneDeviceTypeDimmer:
        {
            if (self.addDeviceFunctionModel.percent == 100) self.addDeviceFunctionModel.percent = 99;
             urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x26&index=0&value=%ld", self.addDeviceFunctionModel.percent];
            break;
        }
            
        case SceneDeviceTypeDoorLock:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x62&index=0&value=%@", (self.addDeviceFunctionModel.isOn == YES ? @"True" : @"False")];
            break;
        }
        default:
            break;
    }
    
    if (_currentEditAttachedDevice) {
        [self sendReqConfigAttachDeviceWithURL:urlStr thermostateBaseUrl:urlBase];
    }else
        [self sendReqAddNewDeviceToSceneWithURL:urlStr thermostateBaseUrl:urlBase];
    }
}

- (void)reqSceneArmConditionActionType:(SceneReqActionType)actionType withArmModel:(ArmModel *)armModelData{
    
    if (!armModelData) return;
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {
        [activity startAnimating];
        NSString *urlStr = nil;
        if (actionType == SceneReqActionTypeAddNew) {
            urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_addcond&scene=%@&cond=%ld&active=%@", ipUrl, self.currenSceneId, armModelData.armId, (armModelData.active ? @"true":@"false")];
        }else if (actionType == SceneReqActionTypeDelete) {
            
           urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_delcond&scene=%@&cond=%ld", ipUrl, self.currenSceneId, armModelData.armId];
            
        }else if (actionType == SceneReqActionTypeEdit) {
            
            urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_setcond&scene=%@&cond=%ld&active=%@", ipUrl, self.currenSceneId, armModelData.armId, (armModelData.active ? @"true":@"false")];
        }
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            
            if (!responseObject) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                if (actionType == SceneReqActionTypeAddNew) {
                   
                    [self.attachDeviceModelList addObject:armModelData];
                    [self resetSceneAddArmSelect];
                    [self.attachDeviceListView reloadData];
                    
                }else if (actionType == SceneReqActionTypeDelete) {
                    
                    [self.attachDeviceModelList removeObject:armModelData];
                    [self.attachDeviceListView reloadData];
                    
                }else if (actionType == SceneReqActionTypeEdit) {
                    
                    [self replaceSceneArmModelListWithData:armModelData];
                    [self.attachDeviceListView reloadData];
                    [self resetSceneAddArmSelect];
                }
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [activity stopAnimating];
            NSLog(@"error:%@",error);
        }];

    }
}
/*
//!由于空调设置开状态后，还需要再发一请求设置模式和值，所以需要有个UrlBase
- (void)sendReqAddNewDeviceToSceneWithURL:(NSString *)urlStr thermostateBaseUrl:(NSString *)urlBase {
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            if (self.addDeviceFunctionModel.deviceType == SceneDeviceTypeThermostat
                && self.addDeviceFunctionModel.isOn
                && ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"] || [self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"cool"] )) {
                //发送设置空调温度请求
                NSString * urlThermostat = [urlBase stringByAppendingFormat:@"&cmd=0x43&index=%d&value=%ld", ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"]?1:2), self.addDeviceFunctionModel.thermostatTemperature];
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                        [Utitlity commonHTTPMethod:urlThermostat responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                            
                            if (!responseObject) return;
                            NSDictionary *retJsonData = responseObject;
                            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                                
                                [self.canSelectDeviceList removeObject:self.selectedDeviceItemData];
                                [self.attachDeviceModelList addObject:self.addDeviceFunctionModel];
                                [self reSetDevListSelect];
                                [self.attachDeviceListView reloadData];
                            }
                            
                        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                            [activity stopAnimating];
                            NSLog(@"error:%@",error);
                            
                        }];
                });
 
            }else {
            
                [self.canSelectDeviceList removeObject:self.selectedDeviceItemData];
                [self.attachDeviceModelList addObject:self.addDeviceFunctionModel];
                [self reSetDevListSelect];
                [self.attachDeviceListView reloadData];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
        
    }];

}

- (void)sendReqConfigAttachDeviceWithURL:(NSString *)urlStr thermostateBaseUrl:(NSString *)urlBase {
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            if (self.addDeviceFunctionModel.deviceType == SceneDeviceTypeThermostat
                && self.addDeviceFunctionModel.isOn
                && ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"] || [self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"cool"] )) {
                //发送设置空调温度请求
                NSString * urlThermostat = [urlBase stringByAppendingFormat:@"&cmd=0x43&index=%d&value=%ld", ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"]), self.addDeviceFunctionModel.thermostatTemperature];
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    [Utitlity commonHTTPMethod:urlThermostat responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        if (!responseObject) return;
                        NSDictionary *retJsonData = responseObject;
                        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                            
                            [self replaceDeviceModelListWithData:self.addDeviceFunctionModel];
                            [self.attachDeviceListView reloadData];
                            [self reSetDevListSelect];
                        }
                        
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        [activity stopAnimating];
                        NSLog(@"error:%@",error);
                        
                    }];
                });
                
            }else {
                
                [self replaceDeviceModelListWithData:self.addDeviceFunctionModel];
                [self.attachDeviceListView reloadData];
                [self reSetDevListSelect];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
        
    }];
    
}

- (void)replaceDeviceModelListWithData:(SceneDeviceModel *)data {
    
    for (NSInteger i=0; i<self.attachDeviceModelList.count; i++) {
        
        SceneDeviceModel *item = self.attachDeviceModelList[i];
        if ([item.deviceId isEqualToString:data.deviceId]) {
            
            [self.attachDeviceModelList replaceObjectAtIndex:i withObject:data];
            break;
        }
    }
    
}
*/
/*
#pragma mark - UITableView Delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SceneDeviceCell *cell = (SceneDeviceCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
    
    [cell.switchBtn addTarget:self action:@selector(resetSceneDeviceCell:) forControlEvents:UIControlEventTouchUpInside];
    
    
    return cell;
}


#pragma mark - 

- (void)resetSceneDeviceCell:(UIButton *)sender {
    
    CGRect btnRect = sender.frame;
    CGPoint p = [sender convertPoint:btnRect.origin toView:self.attachDeviceListView];
    NSIndexPath *indexPath = [self.attachDeviceListView indexPathForRowAtPoint:CGPointMake(0, p.y)];
    //DLog(@"%ld", indexPath.row);
    if (indexPath.row < self.attachDeviceModelList.count) {
    
        [self reSetDevListSelect];
        _currentEditAttachedDevice = YES;
        
        SceneDeviceModel *sceneData = self.attachDeviceModelList[indexPath.row];
        self.addDeviceFunctionModel = [sceneData copy];
        _currentSelectDeviceType = sceneData.deviceType;
        
        [self doChoose:PICKER_VIEW_FUNCTION_LIST_TAG];
        
    }
}
*/

- (void)pickerViewConfirmForFunctionList:(NSInteger)picker_selected_index {
    [super pickerViewConfirmForFunctionList:picker_selected_index];
    
    if (_currentEditAttachedDevice == YES) {
        [self reqConfigSceneDevice:self.addDeviceFunctionModel.deviceId];
    }
}

- (void)pickerViewConfirmForSceneArmState:(NSInteger)picker_selected_index {

    [super pickerViewConfirmForSceneArmState:picker_selected_index];
    if (_currentEditAttachedDevice == YES) {
        [self addNewDeviceToScene:self.sceneAddArmConditionModel];
    }
}

@end
